<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreDepartmentRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $parentId = $this->input('parent_id', 0);
        // 如果 parent_id 为 null，转换为 0
        if ($parentId === null) {
            $parentId = 0;
        }

        // 构建 parent_id 验证规则
        $parentIdRules = ['nullable', 'integer'];
        // 如果 parent_id 不为 0，则必须存在于 departments 表中
        if ($parentId !== 0) {
            $parentIdRules[] = Rule::exists('departments', 'id');
        }

        return [
            'parent_id' => $parentIdRules,
            'name' => [
                'required',
                'string',
                'max:255',
                Rule::unique('departments', 'name')->where(function ($query) use ($parentId) {
                    return $query->where('parent_id', $parentId);
                }),
            ],
            'code' => 'nullable|string|unique:departments',
            'leader' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'status' => 'required|integer|in:' . implode(',', [
                \App\Models\Department::STATUS_DISABLED,
                \App\Models\Department::STATUS_ENABLED,
            ]),
            'sort' => 'nullable|integer',
            'remark' => 'nullable|string',
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages(): array
    {
        return [
            'name.required' => '部门名称不能为空',
            'name.unique' => '同级部门名称不能重复',
            'code.unique' => '部门编码已存在',
            'email.email' => '邮箱格式不正确',
            'status.required' => '状态不能为空',
            'status.in' => '状态值不正确',
            'parent_id.exists' => '父部门不存在',
        ];
    }
}
